<template>
    <el-dialog :visible="groupAvator.dialogAvatorUpload" :custom-class="'avator-upload-wrapper'" :show-close="false" :close-on-click-modal="false" v-loading="upLoading">
        <div class="dialog-avator-header" slot="title">
            修改头像
        </div>
        <div class="dialog-body">
            <el-row>
                <el-col :span="15">
                    <el-tabs v-model="activeName" type="card"  @tab-click="handleClick" class="avator-no-border-show">
                        <el-tab-pane label="默认头像" name="default">
                            <div class="list-default-avator">
                                <ul>
                                    <li v-for="(avator, index) in defaultAvatorArr" @click="defaultAvatorClick(avator, index)" :key="index" :class="[ index == defaultIndex ? 'default-active':'']">
                                        <img :src="avator.sValue" :alt="avator.sName">
                                    </li>
                                </ul>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="自定义头像" name="custom">
                            <div class="custom-avator-wrapper" >
                                <template v-if="!avatorBigImg">
                                    <file-upload 
                                        :file-list.sync="avatorOpt.fileList" 
                                        :file-list-show.sync="avatorOpt.fileListShow"
                                        :upFileType="'image'"
                                        :avator="true"
                                        @onSuccess="onSuccess"
                                        :img-size="2"
                                        ref="avatorUpload"
                                        >
                                        <el-button slot="trigger">上传头像</el-button>
                                        <div slot="tip" class="el-upload__tip">支持jpg、jpeg、png格式2M以内的图片</div>
                                    </file-upload>
                                </template>
                                <template v-if="avatorBigImg">
                                    <div class="avator-upload-img">
                                        <img class="avatorImg" ref="avatorBigImg" :src="avatorBigImg"/>
                                    </div>
                                    <file-upload  v-if="avatorBigImg"
                                        :file-list="avatorOpt.fileList"
                                        :avator="true"
                                        :file-list-show="false" 
                                        :upFileType="'image'"
                                        @onSuccess="onSuccess"
                                        :img-size='2'
                                        ref="reAvatorUpload"           
                                    >
                                    </file-upload>
                                </template>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
                <el-col :span="9">
                    <div class="avator-right-wrapper">
                        <h4>头像预览</h4>
                        <div class="preview">
                            <img v-if="previewsImg" ref="previewsImg" :src="previewsImg" :style="styleObj"/>
                        </div>
                        <p class="tips">90*90像素</p>
                        <div class="old-use-avator">
                            <h4>使用过头像</h4>
                            <ul>
                                <li v-for="(item, index) in historyImg" @click="useOldAvator(item)" :key="index" v-if="item!='null'">
                                    <span><img :src="item"/></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-row type="flex" justify="center">
            <el-col>
                <el-button @click="cancelAvator">取 消</el-button>
                <el-button type="primary" @click="saveAvator" :disabled="disabled">保存头像</el-button>
            </el-col>
        </el-row>
    </el-dialog>
</template>

<script>
import FileUpload from 'components/Upload/fileUpload';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import {getGroupChatDefaultImages, updateGroupChatImg, base64ToFile } from 'api/classAll.js';

export default {
    name: 'AvatorUpload',
    components: {
        FileUpload
    },
    props: {
        groupAvator: {
            type: Object,
            default: {}
        },
        schoolId: {
            type: [String],
            require: true
        },
        historyImg: {
            type: Array,
            default() {
                return []
            }
        },
        pId: {
            type: [String],
            default: ''
        }
    },
    created() {
        this._getGroupChatDefaultImages();
        this.resetStyle();
    },
    data() {
        return {
            activeName: 'default',
            defaultIndex: -1,
            avatorOpt: {
                fileList: [],
                fileListShow: true
            },
            avatorBigImg: '',
            previewsImg: this.groupAvator.avatorUrl || '',
            defaultsImg: '',
            defaultAvatorArr: [],
            upLoading: false,
            styleObj: {},
            avatorUploadImg: this.groupAvator.avatorUrl || '',
            avatorImg: '',
            disabled: true
        }
    },
    watch: {
        defaultsImg(val) {
            if (val) {
                this.resetCropper();
                this.previewsImg = val;
            }
        },
        avatorBigImg(val) {
            if (val) {
                this.defaultIndex = -1;
                this.disabled = false;
            }
        },
        avatorUploadImg(val) {
            if (val) {
                this.disabled = false;
            }
        }
    },
    methods: {
        handleClick() {
            // 
        },
        defaultAvatorClick(avator, index) {
            this.resetDialog();
            this.resetCropper();
            this.resetStyle();
            this.defaultIndex = index;
            this.avatorBigImg = '';
            this.defaultsImg = avator.sValue;
            this.avatorUploadImg = this.defaultsImg;
            
        },
        useOldAvator(imgUrl) {
            this.resetDialog();
            this.resetCropper();
            this.resetStyle();
            this.defaultIndex = -1;
            if (this.avatorObj) {
                this.avatorObj.destroy();
                this.avatorObj = null;
            }           
            this.avatorBigImg = '';
            this.previewsImg = imgUrl;        
            this.avatorUploadImg = imgUrl; 
            
        },
        resetStyle() {
            this.styleObj = {
                'width': '90px',
                'height': '90px',
                'marginLeft': 0,
                'marginTop': 0
            }  
        },
        onSuccess(data) {
            this.resetCropper();
            if (data) {
                data.imgUrl = data.imgUrl.replace(/\.img\./, '.view-img.');
                this.avatorBigImg = data.imgUrl + '?imageView2/2/w/600';
                this.fileName = data.fileName;
            }
            function each(arr, callback) {
                var length = arr.length;
                var i;
                for (i = 0; i < length; i++) {
                    callback.call(arr, arr[i], i, arr);
                }
                return arr;
            }
            var _this = this;
            this.$nextTick(() => {
                var avatorImg = document.querySelector('.avatorImg');
                var previews = document.querySelector('.preview');
                this.avatorObj = new Cropper(avatorImg, {
                    dragMode: 'move',
                    aspectRatio: 1 / 1,
                    autoCropArea: 0.4,
                    guides: false,
                    // highlight: false,
                    viewMode: 1,
                    boxWidth: 450,
                    boxHeight: 250,
                    background: false,
                    minSize: [90, 90],
                    minCropBoxWidth:90,
                    minCropBoxWidth: 90,
                    autoCrop: false,
                    ready() {
                        _this.previewsImg = data.imgUrl;
                        Object.assign(_this.styleObj, {
                            // 'display': ' block',
                            'min-width': ' 0',
                            'min-height': ' 0',
                            'max-width': ' none',
                            'max-height': ' none'
                        })

                        _this.avatorObj.crop();
                    },
                    crop(e) {
                        
                        var data = e.detail;
                        var cropper = _this.avatorObj;
                        var imageData = cropper.getImageData();
                        var previewAspectRatio = data.width / data.height;
                        var previewImage = _this.$refs.previewsImg;
                        if (!previewImage) {
                            return;
                        }
                        var previewWidth = previews.offsetWidth;
                        var previewHeight = previewWidth / previewAspectRatio;
                        var imageScaledRatio = data.width / previewWidth;
                        previews.style.height = previewHeight + 'px';

                        previewImage.style.width = imageData.naturalWidth / imageScaledRatio + 'px';
                        previewImage.style.height = imageData.naturalHeight / imageScaledRatio + 'px';
                        previewImage.style.marginLeft = -data.x / imageScaledRatio + 'px';
                        previewImage.style.marginTop = -data.y / imageScaledRatio + 'px';

                        _this.getImageCanvasData();
                    }
                });
                
            })
        },
        saveAvator() {
            if (this.fileName) {
                this.avatorImg = this.avatorObj.getCroppedCanvas().toDataURL();
                base64ToFile({'fileName': this.fileName, 'contents': this.avatorImg.split('base64,')[1]}).then((res) => {
                    this.avatorUploadImg = res.data.content;
                    // this.avatorUploadImg = res.data.content + '?imageView2/2/w/90/h/90';
                    this.saveImg();
                })
            } else {
                this.saveImg()                                
            }
            this.resetDialog();
        },
        getImageCanvasData() {
            var canvas;
            this.$nextTick(() => {
                var avatorImg = document.querySelector('.avatorImg');
                // var previews = document.querySelectorAll('.preview');
                if (!this.avatorObj) {
                    return;   
                }
                canvas = this.avatorObj.getCroppedCanvas({
                    width: 90,
                    height: 90
                });
                avatorImg.src = canvas.toDataURL();
                this.avatorImg = avatorImg.src;
                // //console.log(this.avatorImg, '----------121212avatorImg');
            });
        },
        saveImg() {
            var chatAvatorData = {
                'fClassId': this.$route.params.classId,
                'fSchoolId': this.schoolId,
                'sImgUrl': this.avatorUploadImg,
                'pId': this.pId
            }
            this.upLoading = true;
            updateGroupChatImg(chatAvatorData).then((data) => {
                this.$message({
                    message: '修改班级群头像成功',
                    type: 'success'
                });
             
                this.groupAvator.dialogAvatorUpload = false;
                this.$emit('getImgData', true);
                this.upLoading = false;
                this.resetStyle();
            }).catch(Error => {
                this.upLoading = false;
            })
        },
        _getGroupChatDefaultImages() { // 获取默认头像
            getGroupChatDefaultImages().then((res) => {
                if (res.data.content) {
                    this.defaultAvatorArr = res.data.content;
                }
            })
        },
        resetDialog() {
            this.avatorOpt.fileList = []; 
            this.$refs.avatorUpload&&this.$refs.avatorUpload.clearFiles();
            this.$refs.reAvatorUpload&&this.$refs.reAvatorUpload.clearFiles();
        },
        cancelAvator() {
            // this.$emit('update:dialogAvatorUpload', false);
            this.groupAvator.dialogAvatorUpload = false;
            if (this.avatorObj) {
                this.avatorObj.destroy();
                this.avatorObj = null;
            }
            this.resetDialog();
        },
        resetCropper() {
            if (this.avatorObj) {
                this.avatorObj.destroy();
                this.avatorObj = null;
                this.fileName = '';
                this.avatorBigImg = '';
            }
        }
    }
}
</script>

<style lang="scss">
    .avator-upload-wrapper{
        li{
            list-style: none;
        }
        width: 720px;
        .dialog-avator-header {
            height: 60px;
            line-height: 60px;
            font-size: 20px;
            text-align: left;
            border-bottom: 1px solid #ddd;  
        }
        .avator-no-border-show{
            .el-tabs__header {
                -webkit-box-shadow: none;
                box-shadow: none;
            }
        }
        .list-default-avator {
            ul{
                overflow: hidden;
                margin-right: -10px;
                padding-left: 10px;
            }
            li{
                float: left;
                position: relative;
                width: 58px;
                height: 58px;
                cursor: pointer;
                margin: 12px 12px 0 0;
                img{
                    width: 100%;
                    height: 100%;
                }
            }
            .default-active::after {
                content:'';
                position: absolute;
                top: 0;
                left: 0;
                width: 58px;
                height: 58px;
                background: url(../../../assets/avator-active.png);
            }
        }
        .custom-avator-wrapper {
            padding: 20px;
            // width: 450px;
            // height: 250px;
            overflow: hidden;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            margin-bottom: 80px;
        }
        .avator-upload-img{
            width: 450px;
            height: 310px;
        }
        .preview, .default-preview{
            overflow: hidden;
            width: 90px;
            height: 90px;
            border-radius: 4px;
            background: #f7f7f9;
            margin-bottom: 8px;
        }
        .avator-right-wrapper{
            padding: 0 0 0 76px;
            h4{
                font-size: 14px;
                margin-bottom: 15px;
                color: #666;
            }
            .tips{
                font-size: 12px;
                color: #999;
            }
            .old-use-avator{
                margin-top: 65px;
                ul{
                    overflow: hidden;
                }
                li{
                    float: left;
                    margin: 5px 5px 0;
                    width: 26px;
                    height: 26px;
                    background: #f7f7f9;
                    img{
                        width: 100%;
                    }
                    cursor: pointer;
                }
            }
        }
    }
    
</style>
